<template>
  <div class="product">
    <!-- 搜索框 -->
    <div class="search">
      <template>
        <el-select
          v-model="searchValue"
          filterable
          clearable
          remote
          @blur="searchBlur"
          @change="searchTextChange"
          reserve-keyword
          @clear="clear"
          placeholder="请输入姓名,如果不更新,点击右侧搜索按钮"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in searchList"
            :key="item.sId"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </template>
      <!-- 搜索按钮 -->
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="onSearchButtonClick"
        plain
      ></el-button>
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        v-has="'add'"
        @click="addStu"
        :disabled="disabled"
        >添加项目</el-button
      >
    </div>
    <!-- 班级选择 -->
    <div class="select-class">
      <!-- 框框 -->
      <el-form>
        <el-form-item label="选择班级:">
          <el-select
            v-model="classes"
            filterable
            @visible-change="classVisible"
            @change="classChange"
            placeholder="请选择"
          >
            <el-option label="全部" value="all"></el-option>
            <el-option
              v-for="(item, index) in classOptions"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <!-- 导出excel -->
    <div class="exportExcel">
      <el-button icon="iconfont icon-excel" @click="exportExcel"
        >导出excel数据</el-button
      >
    </div>
    <!-- 表格 -->
    <div class="stu-table">
      <el-table :data="stuData" v-loading="loading" border style="width: 100%">
        <el-table-column
          prop="headimgurl"
          align="center"
          label="头像"
          width="80"
        >
          <template slot-scope="scope">
            <el-avatar
              shape="square"
              :size="50"
              fit="fill"
              :src="scope.row.headimgurl"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="class" align="center" label="班级">
        </el-table-column>
        <el-table-column prop="productUrl" align="center" label="项目">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              class="btn"
              icon="el-icon-view"
              v-has="'read'"
              @click="$router.push({ path: '/StudentManager/studentProfile' })"
              >查看</el-button
            >
            <el-button
              type="primary"
              class="btn"
              icon="el-icon-edit"
              v-has="'edit'"
              @click="editStu(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              class="btn"
              icon="el-icon-delete"
              v-has="'delete'"
              @click="deleteStu(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        @current-change="changePage"
        :page-size="dataCount"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- dialog弹出框 -->
    <qf-dialog></qf-dialog>
  </div>
</template>
<script>
import dialog from "@/components/dialog";
import * as api from "@/api";
import qee from "qf-export-excel";
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState(["userButtons"]),
  },
  directives: {
    has: {
      inserted: (el, binding, vnode) => {
        //自定义指令中,this是获取不到当前的组件实例的,可以从vnode这个属性中获取,而vnode.context就是当前的组件实例
        // console.log(el);

        //用户的权限['read']
        // console.log(binding);
        //判断当前用户按钮数组中是否包含此字段,如果包含,那么不禁用按钮,如果不包含,那么就要禁用按钮了
        let permissionField = binding.value;
        // console.log(vnode);

        let hasPermission = vnode.context.userButtons.includes(permissionField);

        if (!hasPermission) {
          //当前用户不具备这个权限,禁用按钮
          el.disabled = true;
          //保存原来的类名
          let oldClassName = el.className;
          //加上is-disbaled 显示进状态
          el.className = oldClassName + " " + "is-disabled";
        }
      },
    },
  },
  components: {
    "qf-dialog": dialog,
  },
  data() {
    return {
      params: {
        class: "",
        count: 5,
      },
      dataPage: "", // 页码
      dataCount: 5, // 每页展示的数量
      total: 0, // 总共的数据条数
      classOptions: [],
      disabled: false,
      // 表格的数据对象
      stuData: [],
      // 表格加载动画控制
      loading: false,
      classes: "",
      searchList: [],
      searchValue: "",
      blurSearchValue: "",
      list: [],
    };
  },
  created() {
    this.updateStuTable(); //页面加载的时候,获取表格数据
  },
  methods: {
    addStuRequest(params) {
      //将来通过dialog的eventBus进行调用
    },
    editStuRequest(params) {
      //将来通过dialog的eventBus进行调用
    },
    // 分页器页码发生改变的时候触发的事件
    changePage(page) {
      // 点击分页切换的时候 需要判断是否搜索了 如果搜索了 那么就应该在搜索结果中 进入第后面页码数据
    },
    // 导出excel
    exportExcel() {
      let titleList = [
        {
          title: "头像",
          key: "headimgurl",
        },
        {
          title: "名字",
          key: "name",
        },
        {
          title: "项目地址",
          key: "productUrl",
        },
        {
          title: "班级",
          key: "class",
        },
        {
          title: "城市",
          key: "city",
        },
        {
          title: "创建时间",
          key: "cTime",
        },
      ];

      qee(titleList, this.stuData, "2103学员数据");
    },
    // 班级选择框展开/收起触发的事件
    classVisible(isVisible) {
      //展开的时候需要获取数据
      //调用获取列表的方法
      console.log(isVisible);
      // console.log(123123213);
      if (isVisible) {
        api.getClassesApi().then((res) => {
          this.classOptions = res.data.data;
        });
      }
    },
    // 选择班级
    classChange(query) {
      // console.log("======", query);
      //如果query是all代表要显示所有的数据,后台的设定是,class字段传空字符串就返回所有班级的数据,所以一下用一个三元表达式来处理
      console.log(query);
      if (query !== "all") {
        this.updateStuTable("", "", query);
      } else {
        this.updateStuTable();
      }
    },
    onSearchButtonClick() {
      // 点击搜索按钮
    },
    // 搜索框失去焦点 保持输入框的内容
    searchBlur() {},
    // 编辑学员
    editStu(row) {
      console.log(row);
      this.$bus.$emit("edit-stu", row);
    },
    // 删除学员
    deleteStu(row) {
      console.log(row);
      //从当前表格的行数据中结构出sId
      let { sId } = row;

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消删除",
        type: "warning",
      })
        .then(() => {
          //交互效果,用户点了确定按钮
          api
            .delStuApi(sId)
            .then((res) => {
              console.log(res);
              if (res.data.state) {
                //更新页面
                this.updateStuTable();
                this.$message.success("删除成功");
              } else {
                if (res.data.code === "10026") {
                  this.$message.error(res.data.msg);
                } else {
                  this.$message.error("删除失败,该数据已经被删除");
                }
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("删除出错,检查网络");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 增加学员
    addStu() {
      //因为控制dialog显示和隐藏的属性在dialog组件内部,通过eventBus进行修改, 弹出dialog
      this.$bus.$emit("add-stu");
    },
    // 更新表格数据
    updateStuTable(page = "", count = "", classes = "") {
      //打开loading动画
      this.loading = true;
      //发送请求获取学员数据
      api
        .getStuListApi(page, count, classes)
        .then((res) => {
          console.log(res);
          if (res.data.state) {
            //关闭loading动画
            this.loading = false;
            //更新表格数据
            this.stuData = res.data.data;
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    clear() {
      //情况输入框内容的时候,表格应该显示所有的内容
    },
    // 搜索框选中值发生变化的事件
    searchTextChange(searchText) {
      //   console.log(searchText);
    },
    remoteMethod(query) {
      // 键盘弹起的时候获取输入值
    },
  },
  mounted() {
    //订阅bus更新表格的事件
    this.$bus.$on("update-table", () => {
      this.updateStuTable();
    });
  },
};
</script>
<style scoped>
.search {
  line-height: 60px;
  text-align: left;
  margin: 20px 0;
}
.select-class {
  line-height: 40px;
  text-align: left;
  margin-bottom: 20px;
}
.stu-table .btn {
  width: 65px;
  height: 25px;
  padding: 0;
}
.pagination {
  margin-top: 20px;
}
.exportExcel >>> i.icon-excel {
  color: green;
  font-size: 20px;
  margin-right: 3px;
}

.exportExcel >>> .el-button {
  padding: 4px 7px;
  float: right;
}
.exportExcel {
  margin-bottom: 10px;
  overflow: hidden;
}
</style>
